package com.peng.immodule.util;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.peng.immodule.chat.IMMessage;
import com.peng.immodule.user.IMUser;
import com.peng.immodule.util.HanziToPinyin.Token;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mr.Q on 2018/3/6.
 * 描述：IM 的一个公共工具类，包含如下功能：
 *  1、检查网络状态是否可用
 *  2、检查 SDCard 是否存在
 *  3、
 */

public class IMCommonUtils {

    private static final String TAG = "CommonUtils";

    /**
     * 检查网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }

        return false;
    }

    /**
     * 检查 SDCard 是否存在
     *
     * @return
     */
    public static boolean isSdcardExist() {
        return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    /**
     * 创建表情信息
     *
     * @param toChatUsername
     * @param expressionName
     * @param identityCode
     * @return
     */
//    public static IMMessage createExpressionMessage(String toChatUsername, String expressionName, String identityCode){
//        IMMessage message = IMMessage.createTxtSendMessage("["+expressionName+"]", toChatUsername);
//        if(identityCode != null){
//            message.setAttribute(EaseConstant.MESSAGE_ATTR_EXPRESSION_ID, identityCode);
//        }
//        message.setAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, true);
//        return message;
//    }

    /**
     * 根据消息摘要，设置 ticker 信息
     *
     * @param message
     * @param context
     * @return
     */
//    public static String getMessageDigest(IMMessage message, Context context) {
//        String digest = "";
//        switch (message.getType()) {
//            case LOCATION:
//                if (message.direct() == IMMessage.Direct.RECEIVE) {
//                    digest = getString(context, R.string.location_recv);
//                    digest = String.format(digest, message.getFrom());
//                    return digest;
//                } else {
//                    digest = getString(context, R.string.location_prefix);
//                }
//                break;
//            case IMAGE:
//                digest = getString(context, R.string.picture);
//                break;
//            case VOICE:
//                digest = getString(context, R.string.voice_prefix);
//                break;
//            case VIDEO:
//                digest = getString(context, R.string.video);
//                break;
//            case TXT:
//                EMTextMessageBody txtBody = (EMTextMessageBody) message.getBody();
//                if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_VOICE_CALL, false)){
//                    digest = getString(context, R.string.voice_call) + txtBody.getMessage();
//                }else if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_VIDEO_CALL, false)){
//                    digest = getString(context, R.string.video_call) + txtBody.getMessage();
//                }else if(message.getBooleanAttribute(EaseConstant.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)){
//                    if(!TextUtils.isEmpty(txtBody.getMessage())){
//                        digest = txtBody.getMessage();
//                    }else{
//                        digest = getString(context, R.string.dynamic_expression);
//                    }
//                }else{
//                    digest = txtBody.getMessage();
//                }
//                break;
//            case FILE:
//                digest = getString(context, R.string.file);
//                break;
//            default:
//                EMLog.e(TAG, "error, unknow type");
//                return "";
//        }
//
//        return digest;
//    }

    /**
     * 根据 context 和 资源ID 获取字符串
     * @param context
     * @param resId
     * @return
     */
    static String getString(Context context, int resId){
        return context.getResources().getString(resId);
    }

    /**
     * 获取栈顶的 Activity 的 className
     *
     * @param context
     * @return
     */
    public static String getTopActivity(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);

        if (runningTaskInfos != null){
            return runningTaskInfos.get(0).topActivity.getClassName();
        } else{
            return "";
        }
    }

    /**
     * 根据用户的昵称设置用户的名字的首字母
     *
     * @param user
     */
    public static void setUserInitlLetter(IMUser user) {
        final String DefaultLetter = "#";
        String letter = DefaultLetter;

        final class GetInitialLetter {
            String getLetter(String name) {
                if (TextUtils.isEmpty(name)) {
                    return DefaultLetter;
                }
                //将名字转换为小写字母，并获取第一个字母
                char char0 = name.toLowerCase().charAt(0);
                //如果名字的第一个字母为数字，则返回#
                if (Character.isDigit(char0)) {
                    return DefaultLetter;
                }
                //将汉字转换为拼音，并获取拼音的首字母
                ArrayList<Token> l = HanziToPinyin.getInstance().get(name.substring(0, 1));
                if (l != null && l.size() > 0 && l.get(0).target.length() > 0)
                {
                    Token token = l.get(0);
                    String letter = token.target.substring(0, 1).toUpperCase();
                    char c = letter.charAt(0);
                    if (c < 'A' || c > 'Z') {
                        return DefaultLetter;
                    }
                    return letter;
                }
                return DefaultLetter;
            }
        }

        //若昵称有值，则设置昵称的首字母
        if ( !TextUtils.isEmpty(user.getNick()) ) {
            letter = new GetInitialLetter().getLetter(user.getNick());
            user.setInitialLetter(letter);
            return;
        }

        //若昵称为空，但是userName有值，则去userName的首字母
        if (letter.equals(DefaultLetter) && !TextUtils.isEmpty(user.getUsername())) {
            letter = new GetInitialLetter().getLetter(user.getUsername());
        }
        user.setInitialLetter(letter);
    }

    /**
     * change the chat type to IMConversationType
     * 把 chat 的类型转换成 IMConversationType
     * @param chatType
     * @return
     */
    public static IMConversationType getConversationType(int chatType) {
        if (chatType == EaseConstant.CHATTYPE_SINGLE) {
            return IMConversationType.Chat;
        } else if (chatType == EaseConstant.CHATTYPE_GROUP) {
            return IMConversationType.GroupChat;
        } else {
            return IMConversationType.ChatRoom;
        }
    }

    /**
     * \~chinese
     * 判断是否是免打扰的消息,如果是app中应该不要给用户提示新消息
     * @param message
     * return
     *
     * \~english
     * check if the message is kind of slient message, if that's it, app should not play tone or vibrate
     *
     * @param message
     * @return
     */
    public static boolean isSilentMessage(IMMessage message){
        return message.getBooleanAttribute("em_ignore_notification", false);
    }
}
